package com.etone.smartAudit.service;

import com.etone.smartAudit.mapper.AdminLogMapper;
import com.etone.smartAudit.utils.DateUtil;
import com.etone.smartAudit.utils.Excel.ExcelUtil;
import com.etone.smartAudit.vo.PagerVO;
import com.etone.smartAudit.vo.adminLog.AdminLogVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 蒋学伟
 * @create: 2020-06-16 10:38:21
 * @Description AdminLogService
 */
@Service
@AllArgsConstructor
public class AdminLogService {
    private AdminLogMapper adminLogMapper;

    /**
     * @param adminNickName   用户名称
     * @param startCreateTime 操作开始时间
     * @param endCreateTime   操作结束时间
     * @param module          操作类型
     * @param item            操作动作
     * @param page            当前页
     * @param pageSize        每页显示数量
     * @return
     */
    public PagerVO<AdminLogVO> list(String adminNickName, Date startCreateTime, Date endCreateTime, String module, String item, int page, int pageSize) {
        Page<AdminLogVO> adminLogVOPage = PageHelper.startPage(page, pageSize).doSelectPage(() -> {
            adminLogMapper.findList(adminNickName, startCreateTime, endCreateTime, module, item);
        });
        return PagerVO.of(adminLogVOPage);
    }

    /**
     * 导出日志内容
     *
     * @param adminNickName
     * @param startCreateTime
     * @param endCreateTime
     * @param module
     * @param item
     * @param response
     */
    public void export(String adminNickName, Date startCreateTime, Date endCreateTime, String module, String item, HttpServletResponse response) {
        List<String> header = Arrays.asList("用户名称", "操作类型", "操作动作", "公司名称", "操作时间", "服务器名称", "操作类型");

        List<AdminLogVO> adminLogVOS = adminLogMapper.findList(adminNickName, startCreateTime, endCreateTime, module, item);
        List<List<String>> contents = adminLogVOS.stream().map(adminLogVO ->
                Arrays.asList(adminLogVO.getAdminNickName(), adminLogVO.getModule(), adminLogVO.getItem(), adminLogVO.getAdminCompanyName(), DateUtil.parseDate2String(adminLogVO.getCreateTime(), DateUtil.DF_yyyy_MM_dd_HH_mm_ss), adminLogVO.getServerName(), adminLogVO.getContent())
        ).collect(Collectors.toList());
        ExcelUtil.export("日志", header, contents, response);
    }

    /**
     * 查找日志操作类型
     *
     * @return
     */
    public List<String> listModules() {
        return adminLogMapper.findModules();
    }

    /**
     * 查找日志操作动作
     *
     * @param module
     * @return
     */
    public List<String> listItems(String module) {
        return adminLogMapper.findItems(module);
    }
}

